package com.imay.live.activity.family;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.imay.live.R;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.family.controller.FamilyRankController;
import com.imay.live.model.RankingModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/9/15 0015.
 */

public class FamilyRankActivity extends BaseRequestActivity {

    private final static String KEY_FAMILY_ID = "key_family_id";

    private String loadFamilyRankCommand;
    private FamilyRankController controller;
    private int familyId;
    private int count = 100;

    /**
     * @param context
     */
    public static void startActivity(Context context, int familyid) {
        Intent intent = new Intent(context, FamilyRankActivity.class);
        intent.putExtra(KEY_FAMILY_ID, familyid);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_family_rank;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(R.string.str_family_rank_title);
        familyId = getIntent().getIntExtra(KEY_FAMILY_ID, -1);
        controller = (FamilyRankController) FamilyRankController.Builder.create(this, FamilyRankController.class).build();
        loadFamilyRank();
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        super.onRequestSuccess(command, data);
        if (command.equals(loadFamilyRankCommand)) {
            Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
            }.getType());
            if (result.data.containsKey("ranks") && result.data.containsKey("myRank")) {
                ArrayList<RankingModel> rankingModels = JSON.parseObject(result.data.getString("ranks"), new TypeReference<ArrayList<RankingModel>>() {
                }.getType());
                RankingModel rankingModel = JSON.parseObject(result.data.getString("myRank"), new TypeReference<RankingModel>(){}.getType());
                controller.setRankData(rankingModels);
                controller.setMyRank(rankingModel);
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
    }

    private void loadFamilyRank() {
        if (familyId == -1) {
            return;
        }
        loadFamilyRankCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilyRank(familyId, "total", 0, count)).setTag(this.hashCode()).request(this);
    }
}
